package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.*;
import com.itheima.reggie.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper,Orders> implements OrdersService {

    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    AddressBookMapper addressBookMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Override
    public R<String> submit(Orders orders) {
        // 获取用户id
        Long userId = BaseContext.getCurrentId();
        //查看购物车数据  select * from shopping_cart where user_id = ?
        LambdaQueryWrapper<ShoppingCart> shoppingCartlqw = new LambdaQueryWrapper<>();
        shoppingCartlqw.eq(ShoppingCart::getUserId, userId);
        //获取用户购物车数据
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectList(shoppingCartlqw);
        // 查询用户数据 select * from user where id = ?
        User user = userMapper.selectById(userId);

        //自动生成订单号
        long orderId = IdWorker.getId();
        orders.setStatus(1);
        BigDecimal totalAmount = new BigDecimal(0);//总价
        //遍历购物车保存订单明细
        for (ShoppingCart shoppingCart : shoppingCarts) {
            //拷贝数据 把购物车信息拷贝到订单详情
            OrderDetail orderDetail = new OrderDetail();
            //设置订单id
            orderDetail.setOrderId(orderId);

            BeanUtils.copyProperties(shoppingCart, orderDetail);
            //设置订单号
            orderDetail.setOrderId(orderId);
            // amount 金额单独设置 数量  *  单价
            BigDecimal price = shoppingCart.getAmount();
            BigDecimal number = new BigDecimal(shoppingCart.getNumber()); //获取数量
            orderDetail.setAmount(price.multiply(number));//计算总价
            BigDecimal orderDetailAmount = orderDetail.getAmount();
            totalAmount = totalAmount.add(orderDetailAmount);
            //调用订单详情方法更新订单信息
            orderDetailMapper.insert(orderDetail);
        }
        // 根据地址id查询地址数据 select * from address_book where id = ?
        //获取地址簿收货人信息    用户地址 String address = orders.getAddress();??
        AddressBook addressBook = addressBookMapper.selectById(orders.getAddressBookId());
        // 保存订单数据，设置属性
        orders.setAmount(totalAmount);
        orders.setId(orderId);
        orders.setNumber(String.valueOf(orderId));
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);//1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setUserId(userId);
        User user1 = userMapper.selectById(userId);
        orders.setUserName(user1.getName());//设置用户名
        orders.setConsignee(addressBook.getConsignee());//收货人
        orders.setPhone(addressBook.getPhone());
        //设置地址 省+市+区域+详细地址
      /*  StringBuilder sb = new StringBuilder();
        sb.append()*/
        orders.setAddress(
                (addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                        + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                        + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                        + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        this.save(orders);
        // 删除当前用户的购物车数据  delete from shopping_cart where user_id = ?
        shoppingCartMapper.delete(shoppingCartlqw);
        return R.success("清空购物车成功");
    }
}
